function Ajax() {}

Ajax.debug = false;

//Ajax.okMessage = '[OK]';

Ajax.isOk = function(str) {
	return (str == '[OK]') || (str == "'[OK]'");
}

Ajax.doPostQuery = function(url,h,onfinish) {

	var instance = new Ajax();

	instance.getQuery = '';
	instance.postQuery = Ajax.composeQuery(h)
	instance.contentType = 'application/x-www-form-urlencoded';

	instance.onfinish = onfinish;
	instance.send(url);
}

Ajax.doGetQuery = function(url,h,onfinish) {

	var instance = new Ajax();

	instance.getQuery = '?' + Ajax.composeQuery(h);

	instance.onfinish = onfinish;
	instance.send(url);
}

/* impl */

Ajax.prototype.send = function(url) {

	try{

		var me = this;

		this.req = Ajax.getHttpRequest();
		this.req.onreadystatechange = function() { Ajax.waiting(me); }
		this.req.open((this.postQuery) ? 'POST' : 'GET', url + this.getQuery, true);

		if (this.contentType)
			this.req.setRequestHeader('Content-Type',this.contentType);

		this.req.send(this.postQuery);

	} catch (err) {
		Ajax.onerror('can not create newRequest - ' + err);
	}
}

Ajax.waiting = function(me) {

	try {
		var httpStatus = me.req.status;
		var readyState = me.req.readyState; // IE say here "unknown error" :-/
	} catch(e) {
		return;
	}

	if (readyState == 4) {
		if (httpStatus == 200 || httpStatus == 0){
			if (Ajax.debug) Debug.show('httpStatus = ' + httpStatus + '; response: ' + me.req.responseText);
//			me.onfinish( Ajax.responsePostprocess(me.req.responseText) );
			me.onfinish(me.req.responseText);
		} else {
			Ajax.onerror('status ' + httpStatus + '; txt = ' + me.req.responseText);
		}
	}
}

Ajax.composeQuery = function(hParams) {
	var query = '';
	for (var param in hParams) {
		query +=
			param + '=' +
//			hParams[param].replace(new RegExp('\\+','g'), '%2B') + '&';
			hParams[param] + '&';
	}
	return query;
}

Ajax.getHttpRequest = function() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) {
	   	return new ActiveXObject("Microsoft.XMLHTTP");
  	} else {
		Ajax.error('Can not create HttpRequest. May be used very old browser.');
  	}
}

Ajax.onerror = function(err) {
	if (!err) err = '';
	document.writeln('AJAX ERROR: ' + err);
}

Ajax.test = function() {
	var x = Ajax.getHttpRequest();
}

Ajax.test();


function form2hash(form) {

	var hRes = {};

	for(var key in form.elements) {

		var elem = form.elements[key];
		if (!elem || !elem.name) continue;

		if (typeof elem.value != 'undefined') {
			hRes[elem.name] = elem.value;
		} else if (typeof elem.innerHTML  != 'undefined') {
			hRes[elem.name] = elem.innerHTML;
		}
	}
	return hRes;
}

